package economy;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.logging.Logger;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import main.Plugin;

public class EconomyHandler implements CommandExecutor, Listener {
	private static HashMap<Player, Money> economy;
	private final Connection connection;

	public EconomyHandler(Connection connection, Plugin plugin) {
		this.connection = connection;
		economy = new HashMap<Player, Money>();
		plugin.getCommand("pay").setExecutor(this);
		plugin.getCommand("balance").setExecutor(this);
		plugin.getCommand("check").setExecutor(this);
		Bukkit.getPluginManager().registerEvents(this, plugin);
	}

	@Override
	public boolean onCommand(CommandSender sender, Command command,
			String label, String[] args) {
		if (sender instanceof Player) {
			Player player = (Player) sender;
			if (command.getName().equalsIgnoreCase("pay")) {
				Player recipient = Bukkit.getPlayer(args[0]);
				int payment = Integer.parseInt(args[1]);
				if (recipient.isOnline()
						&& economy.get(player).withdraw(payment)) {
					economy.get(recipient).deposit(payment);
				}
			}
			if (command.getName().equalsIgnoreCase("balance")) {
				economy.get(player).checkBalance();
			}
		} else {
			if (command.getName().equalsIgnoreCase("check")) {
				Player player = Bukkit.getPlayer(args[0]);
				Logger.getLogger("Minecraft").info(
						args[0] + ": " + economy.get(player).amount());
			}
			if (command.getName().equalsIgnoreCase("pay")) {
				Player player = Bukkit.getPlayer(args[0]);
				int payment = Integer.parseInt(args[1]);
				economy.get(player).deposit(payment);
			}
		}
		return false;
	}

	@EventHandler
	private void playerJoin(PlayerJoinEvent event) {
		Player player = event.getPlayer();
		try {
			String query = "SELECT amount FROM money WHERE username = '"
					+ player.getName() + "'";
			ResultSet data = connection.prepareStatement(query).executeQuery();
			if (data.last()) {
				economy.put(player, new Money(player, data.getInt("amount")));
			} else {
				try {
					economy.put(player, new Money(player, 0));
					query = "INSERT INTO money(username, amount) VALUES ('"
							+ player.getName() + "',0)";
					connection.prepareStatement(query).executeUpdate();
				} catch (Exception e) {
					Logger.getLogger("Minecraft").info(
							"Unable to insert money info for: " + query);
				}
			}
		} catch (Exception e) {
			Logger.getLogger("Minecraft").info(
					"Unable to query money info for: " + player.getName());
		}
	}

	@EventHandler
	private void playerQuit(PlayerQuitEvent event) {
		Player player = event.getPlayer();
		int amount = economy.get(player).amount();
		String update = "UPDATE money SET amount = " + amount
				+ " WHERE username = '" + player.getName() + "'";
		try {
			PreparedStatement statement = connection.prepareStatement(update);
			statement.executeUpdate();

		} catch (Exception e) {
			Logger.getLogger("Unable to update money info for: "
					+ player.getName());
		}
		economy.remove(event.getPlayer());
	}
}
